<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.userName"
        placeholder="名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.email"
        placeholder="邮箱"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.phoneNumber"
        placeholder="手机"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        v-if="checkPermission(['AbpIdentity.Users.Create'])"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button>
      <el-button
        v-if="false"
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >导出</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      style="width: 100%"
      :data="list"
      @sort-change="sortChange"
    >
      <el-table-column label="名称" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" width="210px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机" width="210px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.phoneNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="creationTime" sortable="custom" label="创建时间" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.creationTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <el-button v-if="checkPermission(['AbpIdentity.Users.Update'])" type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(row)">编辑</el-button>
          <el-button v-if="row.userName!='admin' && checkPermission(['AbpIdentity.Users.Delete'])" size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="150px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="名称" prop="userName">
          <el-input v-model="temp.userName" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" />
        </el-form-item>
        <el-form-item v-if="dialogStatus==='create'" label="密码" prop="password">
          <el-input v-model="temp.password" show-password />
        </el-form-item>
        <el-form-item label="真实名字">
          <el-input v-model="temp.surname" />
        </el-form-item>
        <el-form-item label="手机" prop="phoneNumber">
          <el-input v-model="temp.phoneNumber" />
        </el-form-item>
        <el-form-item label="二次确认">
          <el-switch v-model="temp.twoFactorEnabled" active-color="#13ce66" inactive-color="#dcdfe6" />
        </el-form-item>
        <el-form-item label="锁定">
          <el-switch v-model="temp.lockoutEnabled" active-color="#13ce66" inactive-color="#dcdfe6" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="temp.roleNames" multiple placeholder="请选择">
            <el-option v-for="item in roleOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button :loading="loading" type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUsers, getUser, createUser, updateUser, deleteUser, getUserRoles } from '@/api/user'
import { getRoles } from '@/api/role'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { checkPhone } from '@/utils/validate'
import checkPermission from '@/utils/permission' // 权限判断函数

export default {
  name: 'User',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        userName: undefined,
        email: undefined,
        phoneNumber: undefined,
        sorting: 'creationTime'
      },
      roleOptions: [],
      temp: {
        id: '',
        password: '',
        userName: '',
        name: '',
        surname: '',
        email: '',
        phoneNumber: '',
        twoFactorEnabled: false,
        lockoutEnabled: true,
        concurrencyStamp: '',
        roleNames: []
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑用户',
        create: '添加用户'
      },
      rules: {
        userName: [{ required: true, message: '登录名必须填写', trigger: 'blur' }],
        email: [{ required: true, type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
        phoneNumber: [{ required: false, validator: checkPhone, trigger: 'blur' }]
      },
      downloadLoading: false,
      loading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    checkPermission,
    getList() {
      this.listLoading = true
      const params = {
        filter: this.listQuery.userName,
        sorting: this.listQuery.sorting,
        skipCount: (this.listQuery.page - 1) * this.listQuery.limit,
        maxResultCount: this.listQuery.limit
      }
      getUsers(params).then(response => {
        this.list = response.data.items
        this.total = response.data.totalCount
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'creationTime') {
        this.sortByCreationTime(order)
      }
    },
    sortByCreationTime(order) {
      if (order === 'ascending') {
        this.listQuery.sorting = 'creationTime'
      } else {
        this.listQuery.sorting = 'creationTime desc'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: '',
        password: '',
        userName: '',
        name: '',
        surname: '',
        email: '',
        phoneNumber: '',
        twoFactorEnabled: false,
        lockoutEnabled: true,
        concurrencyStamp: '',
        roleNames: []
      }
    },
    handleCreate() {
      this.resetTemp()
      getRoles().then(response => {
        const { data } = response
        const roles = data.items.map(v => {
          return { key: v.name, display_name: v.name }
        })
        this.roleOptions = roles
      })
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          this.temp.name = this.temp.userName
          createUser(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加用户成功',
              type: 'success',
              duration: 2000
            })
          }).catch(err => {
            console.log(err)
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    handleUpdate(row) {
      const { id } = row
      this.temp.roleNames = []
      getUser(id).then(response => {
        // this.temp = Object.assign({}, response.data) // copy obj
        this.temp.id = response.data.id
        this.temp.userName = response.data.userName // copy obj
        this.temp.name = response.data.name // copy obj
        this.temp.surname = response.data.surname // copy obj
        this.temp.email = response.data.email // copy obj
        this.temp.phoneNumber = response.data.phoneNumber // copy obj
        this.temp.twoFactorEnabled = response.data.twoFactorEnabled // copy obj
        this.temp.lockoutEnabled = response.data.lockoutEnabled // copy obj
        this.temp.concurrencyStamp = response.data.concurrencyStamp
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
      getRoles().then(response => {
        const { data } = response
        const roles = data.items.map(v => {
          return { key: v.name, display_name: v.name }
        })
        this.roleOptions = roles
        getUserRoles(id).then(response => {
          const { items } = response.data
          const roles = items.map(v => v.name)
          this.temp.roleNames = roles // copy obj
        })
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          const tempData = Object.assign({}, this.temp)
          const { id } = this.temp
          updateUser(id, tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        const { id } = row
        deleteUser(id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
          // const index = this.list.indexOf(row)
          // this.list.splice(index, 1)
        })
      }).catch(() => {
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    }
  }
}
</script>
